package tts.dao;
// Generated 25-nov-2013 10.10.25 by Hibernate Tools 4.0.0

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import tts.model.Groups;
import tts.model.Roles;
import tts.model.Users;

/**
 * Home object for domain model class Users.
 * @see .Users
 * @author Hibernate Tools
 */
@Repository("usersHome")
@Transactional(propagation = Propagation.REQUIRED)
public class UsersHome {

	private static final Log log = LogFactory.getLog(UsersHome.class);
	@PersistenceContext
	private EntityManager entityManager;
	@Autowired
	private RolesHome rolesHome;
	@Autowired
	private GroupsHome groupsHome;

	public void insert(Users transientInstance) throws RuntimeException {
		log.info("persisting Users instance");
		try {
			entityManager.persist(transientInstance);
			log.info("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public Users update(String username, Users newUser, ArrayList<String> rolesList, ArrayList<String> groupsList) throws RuntimeException {
		log.info("updating Users instance");
		try {
			Users result =this.findByUsername(username);
			result.setUsername(newUser.getUsername());
			result.setPassword(newUser.getPassword());
			Collection<Roles> allRoles = rolesHome.findAll();
			for (Roles currentRole : allRoles) {
				if (rolesList.contains(currentRole.getRoleName())) {
					if (!(result.getRolesList().contains(currentRole)))
						result.getRolesList().add(currentRole);
				} else if (result.getRolesList().contains(currentRole))
					result.getRolesList().remove(currentRole);
			}
			Collection<Groups> allGroups = groupsHome.findAll();
			for (Groups currentGroup : allGroups) {
				if (groupsList.contains(currentGroup.getGroupName())) {
					if (!(result.getGroupsList().contains(currentGroup)))
						result.getGroupsList().add(currentGroup);
				} else if (result.getGroupsList().contains(currentGroup))
					result.getGroupsList().remove(currentGroup);
			}
			log.info("update successful");
			return result;
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(String username) throws RuntimeException {
		log.info("removing Users instance");
		Users user = new Users();
		try {
			Users u = this.findByUsername(username);
			user = entityManager.find(Users.class, u.getUsers_id());
			user.setEnabled(false);
			log.info("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	public void deletePhisical(Users persistentInstance) {
		log.info("removing permanently Users instance");
		try {
			entityManager.remove(persistentInstance);
			log.info("remove successful");
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	public void enable(String username) throws RuntimeException {
		log.info("enabling Users instance");
		Users user = new Users();
		try {
			user = this.findByUsername(username);
			user.setEnabled(true);
			log.info("enable successful");
		} catch (RuntimeException re) {
			log.info("enable failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public Collection<Users> findAll() throws RuntimeException {
		log.info("getting all enabled users in db");
		try {
			Collection<Users> list = entityManager.createQuery("from Users where enabled=1 order by username").getResultList();
			log.info("get successful");
			return list;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public Collection<Users> findDisabled() throws RuntimeException {
		log.info("getting all disabled users in db");
		try {
			Collection<Users> list = entityManager.createQuery("from Users where enabled=0 order by username").getResultList();
			log.info("get successful");
			return list;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public Users findByUsername(String username) throws RuntimeException {
		log.info("getting Users instance with username: " + username);
		Users user = null;
		try {
			List<Users> list = entityManager.createQuery("from Users where username='"+username+"'").getResultList();
			if (list.isEmpty()) return user;
			else user = list.get(0);
			log.info("get successful");
			return user;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public void changePwd(String username, String newPassword) throws RuntimeException {
		log.info("changing password for user: " + username);
		try {
			Users u = this.findByUsername(username);
			u.setPassword(newPassword);
			log.info("pwd change successful");
		} catch (RuntimeException re) {
			log.error("pwd change failed", re);
			throw re;
		}
	}
}